package dao;

import beans.Word;
import db.DBQuery;

import java.util.List;

public class WordDAO extends CommonDAO<Word> {

    public final static WordDAO ME = new WordDAO();

    @Override
    protected String tableName() {
        return new Word().tableName();
    }

    public Word getByWordString(String word_string) {
        String sql = "select * from " + tableName() + " where word_string=? limit 1";
        return DBQuery.read_bean(Word.class, sql, word_string);
    }

    public List<Word> listNewWords(int num) {
        String sql = "select * from " + tableName() + " order by id desc limit ?";
        return DBQuery.query_list(Word.class, sql, num);
    }

    public List<Word> listAllWords() {
        String sql = "select * from " + tableName();
        return DBQuery.query_list(Word.class, sql);
    }

    /**
     * 从表中随机获取一个单词
     * 基本思路就是在 (0，最大id] 之间随机生成一个整数，然后取id大于等于这个数的记录
     */
    public Word getRandomWord() {
        String sql = "select * from osd_word where id >= (select round(rand()*(select MAX(id) from osd_word))) order by id limit 1";
        return DBQuery.read_bean(Word.class, sql);
    }
}
